// pages/productOrderRecord/productOrderRecord.js
const app = getApp()
const request = require('../../utils/request')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    statusBarHeight: app.globalData.statusBarHeight,
    screenHeight: 0,
    couponDialog: false,
    productInfo: {},
    projectNumber: 1,
    sellPrice: 0,
    totalPrice: 0,
    allPrice: 0,
    agreePolicy: true,
    btnLoading: false,
    couponList: [],
    token: wx.getStorageSync('lmtc_token')
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    request.http('/shop/shop-goods/get-by-id', 'GET', { id: options.id })
    .then(res => {
      let data = res.data
      if (data.code == 200) {
        console.log('商品信息：', data)
        this.setData({
          screenHeight: wx.getSystemInfoSync().screenHeight,
          productInfo: data.data,
          sellPrice: data.data.sellPrice,
          totalPrice: data.data.sellPrice,
          allPrice: data.data.originalPrice
        })
        this.getCoupon()
      }
    })
  },
  /**
   * 减少商品
   */
  projectSub() {
    let projectNumber = this.data.projectNumber
    let sellPrice = this.data.productInfo.sellPrice
    let originalPrice = this.data.productInfo.originalPrice
    if (projectNumber <= 1) {
      wx.showToast({
        title: '最少购买1件商品',
        icon: 'none'
      })
      return
    }
    projectNumber--
    this.setData({
      projectNumber,
      totalPrice: projectNumber * sellPrice,
      allPrice: projectNumber * originalPrice,
      checkedCouopn: {},
      couponIndex: -1,
      subtract: 0
    })
    this.getCoupon()
  },
  /**
   * 增加商品
   */
  projectAdd() {
    let projectNumber = this.data.projectNumber
    let sellPrice = this.data.productInfo.sellPrice
    let originalPrice = this.data.productInfo.originalPrice
    if (projectNumber >= this.data.productInfo.stock) {
      wx.showToast({
        title: '当前库存仅剩' + this.data.productInfo.stock + '件商品',
        icon: 'none'
      })
      return
    }
    projectNumber++
    this.setData({
      projectNumber,
      totalPrice: projectNumber * sellPrice,
      sellPrice: projectNumber * sellPrice,
      allPrice: projectNumber * sellPrice,
      checkedCouopn: {},
      couponIndex: -1,
      subtract: 0
    })
    this.getCoupon()
  },
      /**
   * 授权登录
   */
  bindGetUserInfo: function (e) {
    console.log('授权登录')
    let that = this;
    // let url = e.currentTarget.dataset.url
    let userInfo = e.detail.userInfo;
    wx.setStorageSync('lmtc_userInfo', userInfo)
    if (userInfo) {
      this.setData({
        userInfo: userInfo
      })
      wx.login({
        success: res => {
          that.getToken(res.code);
        }
      });
    }
  },
   /**
   * 获取Token
   * @param {String} code 微信返回的用户code
   * @param {Number} index 当前专属停车按钮索引
   */
  getToken(code) {
    let that = this
    let info = this.data.userInfo;
    let url = '/customer/info/authorize'
    let params = {
      avatar: info.avatarUrl,
      code: code,
      nickname: info.nickName,
      sex: info.gender == 0 ? 'UNKNOWN' : info.gender == 1 ? 'MEN' : 'WOMEN',
    }
    request.http(url, 'POST', params)
      .then(res => {
        var data = res.data
        if (data.code == 200) {
          let token = data.data.token
          // let parkData = this.data.parkList[index]
          wx.setStorageSync('lmtc_token', token)
          wx.setStorageSync('lmtc_customerId', data.data.customerId)
          that.setData({
            token: token
          })
          // wx.navigateTo({
          //   url: '../vipCharge/vipCharge?parkData=' + JSON.stringify(parkData) + '&index=1',
          // })
        }
      })
  },
  /**
   * 勾选用户政策
   */
  bindAgreePolicy() {
    this.setData({
      agreePolicy: !this.data.agreePolicy
    })
  },
  /**
   * 购买
   */
  toPay() {
    if (!this.data.agreePolicy) {
      wx.showToast({ title: '请先同意购买协议', icon: 'none' })
      return
    }
    this.setData({ btnLoading: true })
    let couponList = this.data.couponList
    let couponIndex = this.data.couponIndex
    let productInfo = this.data.productInfo
    let parmas = {
      goodsId: productInfo.id,
      payableAmount: this.data.allPrice,
      paidAmount: this.data.totalPrice,
      // paidAmount: 0.01,
      // payableAmount: 0.01,
      custTicketId: couponList[couponIndex] ? couponList[couponIndex].id : '',
      quantity: this.data.projectNumber,
      shopId: productInfo.shopId
    }
    let _this = this
    request.http('/shop/shop-order/buyGoods', 'POST', parmas)
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          let payInfo = data.data
          wx.requestPayment({
            timeStamp: payInfo.timeStamp,
            nonceStr: payInfo.nonceStr,
            package: payInfo.package,
            signType: payInfo.signType,
            paySign: payInfo.paySign,
            success(res) {
              _this.setData({ btnLoading: false })
              wx.showToast({
                title: '购买成功',
                success() {
                  wx.redirectTo({
                    url: '/pages/productOrder/productOrder',
                  })
                }
              })
            },
            fail(res) {
              console.log(res)
              _this.setData({ btnLoading: false })
             }
          })
        }
      })
  },
  /**
   * 打开优惠券弹窗
   */
  showCouponDialog() {
    this.setData({
      couponDialog: true
    })
  },
  /**
   * 查询优惠券
   */
  getCoupon() {
    let that = this
    let url = '/customer/ticket/getNotExpiredValidTicket'
    // let type = this.data.orderData.type
    let parmas = {
      cardType: 10,
      amount: this.data.totalPrice,
      goodsId: this.data.productInfo.id
    }
    if(this.data.token != null && this.data.token != ''){
      request.http(url, 'POST', parmas)
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          let coupon = data.data
          for (var i = 0; i < coupon.length; i++) {
            coupon[i].checked = false
          }
          that.setData({
            couponList: coupon
          })
        }
      })
    }
  },
  /**
   * 选择优惠券
   * @param {*} e 
   */
  getDiscount(e) {
    let index = e.currentTarget.dataset.index
    let couponIndex = this.data.couponIndex
    let couponList = this.data.couponList
    console.log('当前选项：', index)
    console.log('旧选项：', couponIndex)
    //  再次点击取消选择
    if (index == couponIndex) {
      couponList[index].checked = false
      this.setData({
        checkedCouopn: {},
        couponIndex: -1,
        subtract: 0
      })
    } else {
      for (var i = 0; i < couponList.length; i++) {
        if (index == i) {
          couponList[i].checked = true
        } else {
          couponList[i].checked = false
        }
      }
      this.setData({
        checkedCouopn: couponList[index],
        couponIndex: index
      })
    }
    this.setData({
      couponList: couponList
    })
    if (this.data.checkedCouopn.ticketId) {
      this.countCoupon()
    }
    this.hideCouponDialog()
  },
  /**
   * 计算优惠价格
   */
  countCoupon() {
    let that = this
    let url = '/customer/ticket/getDiscountAmontWithTicket'
    let parmas = { 
      paidAmount: this.data.totalPrice,
      receivableAmount: this.data.sellPrice,
      ticketId: this.data.checkedCouopn.ticketId,
      custTicketId: this.data.checkedCouopn.id,
      rentType: 10,
      customerId: wx.getStorageSync('lmtc_customerId')
    }
    request.http(url, 'POST', parmas)
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          console.log('计算优惠价格', data)
          that.setData({
            totalPrice: data.data.paidAmount,
            subtract: data.data.discountAmount
          })
        }
      })
  },
  // /**
  //  * 显示优惠券弹窗
  //  */
  // showCouponDialog() {
  //   if (this.data.couponList.length <= 0) {
  //     wx.showToast({
  //       title: '暂无优惠券可用',
  //       icon: 'none'
  //     })
  //     return
  //   }
  //   this.setData({
  //     couponDialog: true
  //   })
  // },
  /**
   * 隐藏优惠券弹窗
   */
  hideCouponDialog() {
    this.setData({
      couponDialog: false
    })
  },
})